package top.hypnos.bigdata.filesystem.record;

import org.apache.commons.codec.binary.Hex;

import java.io.IOException;
import java.io.InputStream;

public class ObjectInputStreamImpl implements ObjectInputStream {

    private final InputStream in;

    public ObjectInputStreamImpl(InputStream in) {
        this.in = in;
    }

    @Override
    public int readInt() throws IOException {
        final var bytes = new byte[4];
        final var cnt = in.read(bytes);
        if (cnt < bytes.length) {
            throw new IOException("No enough data left in the InputStream, expected length is " + bytes.length
                    + " and the actual content is: " + Hex.encodeHexString(bytes, true));
        }
        return (bytes[0] & 0xff) << 3 | (bytes[1] & 0xff) << 2 | (bytes[2] & 0xff) << 1 | (bytes[3] & 0xff);
    }

    @Override
    public byte[] readBytes() throws IOException {
        final var length = readInt();
        if (length == 0) {
            return null;
        }
        final var bytes = new byte[length];
        final var cnt = in.read(bytes);
        if (cnt < bytes.length) {
            throw new IOException("No enough data left in the InputStream, expected length is " + bytes.length
                    + " and the actual content is: " + Hex.encodeHexString(bytes, true));
        }
        return bytes;
    }

}
